import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { Router, UrlTree } from '@angular/router';
import { NzModalService } from 'ng-zorro-antd/modal';
import { NzMessageService } from 'ng-zorro-antd/message';
import { ProductListItem } from 'src/app/model/product';
import { ProductCategoryApiService } from 'src/app/api/product-category-api.service';
import { ProductApiService } from '../../../api/product-api.service';
import { map } from 'rxjs/operators';
import { HttpParams } from '@angular/common/http';


@Component({
  selector: 'app-product',
  templateUrl: './product.component.html',
  styleUrls: ['./product.component.less', '../../../styles/container.css']
})
export class ProductComponent implements OnInit {
  searchForm!: FormGroup;
  brandOptions: { value: string, label: string }[];
  cateOptions;
  publishStatuOptions = ['上架', '下架'];
  verifyStatuOptions = ['审核通过', '未审核'];
  products = new Array<ProductListItem>();
  thChecked = false;
  thIndeterminate = false;
  setOfCheckedId = new Set<number>();
  batchOperate: string;
  operateOptions;
  pageIndex = 1;
  total: number;
  pageSize = 5;
  publishStatusLoading: boolean;
  newStatusLoading: boolean;
  recommandStatusLoading: boolean;


  constructor(
    private fb: FormBuilder,
    private router: Router,
    private modal: NzModalService,
    private message: NzMessageService,
    private productApi: ProductApiService,
    private productCateApi: ProductCategoryApiService,
  ) {
    this.operateOptions = [
      { label: '商品上架', value: 'publishOn' },
      { label: '商品下架', value: 'publishOff' },
      { label: '设为推荐', value: 'recommendOn' },
      { label: '取消推荐', value: 'recommendOff' },
      { label: '设为新品', value: 'newOn' },
      { label: '取消新品', value: 'newOff' },
      { label: '转移到分类', value: 'transferCategory' },
      { label: '移入回收站', value: 'recycle' }]
  }

  ngOnInit(): void {
    this.searchForm = this.fb.group({
      keyword: [''],
      productSn: [''],
      productCate: [''],
      brandId: [''],
      publishStatus: [''],
      verifyStatus: [''],
    });
    this.getBandOptionFromServer();
    this.getCateOptionFromServer();
    this.getProductsFromServer();



  }

  // TODO: 商品列表查询与后端的交互
  onSubmit() {
    console.warn(this.searchForm.value);
  }

  resetForm() {
    this.searchForm.reset()
  }

  handleAdd() {
    this.router.navigateByUrl('pms/addProduct')
  }

  onAllChecked(e: boolean) {
    this.products.forEach(item => this.updateCheckedSet(item.id, e));
    this.refreshCheckedStatus();
  }

  // TODO:从后端获取品牌选项
  getBandOptionFromServer() {
    this.brandOptions = [
      { label: '小米', value: '1' },
      { label: '七匹狼', value: '2' },
      { label: '苹果', value: '3' },
      { label: '华为', value: '4' },
    ]
  }

  // 从后端获取商品分类信息
  getCateOptionFromServer() {
    this.productCateApi.fetchListWithChildren()
      .pipe(
        map(item => {
          return item.map(cate => {
            const result = {
              value: cate.id,
              label: cate.name,
              children: cate.children.map(childCate => {
                return {
                  value: childCate.id,
                  label: childCate.name,
                  isLeaf: true
                }
              })
            }
            return result;
          })
        })
      )
      .subscribe(
        option => {
          this.cateOptions = option;
        }
      )
  }


  // 从后端获取商品列表
  getProductsFromServer() {
    const params = new HttpParams({
      fromObject: {
        'pageNum': this.pageIndex.toString(),
        'pageSize': this.pageSize.toString()
      }
    })
    this.productApi.fetchList(params).subscribe(
      respons => {
        this.setOfCheckedId.clear();
        this.total = respons.total;
        this.products = respons.list;
      }
    )
  }

  oneItemChecked(id: number, checked: boolean) {
    this.updateCheckedSet(id, checked);
    this.refreshCheckedStatus()
  }

  // TODO: SKU编辑的实现
  handleSKUEditer(productId: number) {
    console.log(productId);
  }


  // TODO: 上架状态改变的后端交互
  handlePublishStatusClick(productId: number,) {
    console.log(productId);
  }

  // TODO: 新品状态改变的后端交互
  handleNewStatusClick(productId: number,) {
    console.log(productId);
  }

  // TODO: 推荐状态改变的后端交互
  handleRecommandStatusClick(productId: number,) {
    console.log(productId);
  }


  // TODO: 审核详情的功能实现
  handleShowVerifyDetaile(productId: number) {
    console.log(productId);
  }

  // TODO: 查看的功能实现
  handleShowProduct(productId: number) {
    console.log(productId);
  }


  // TODO: 编辑的功能实现
  handleUpdataProduct(productId: number) {
    let urlTree: UrlTree = this.router.parseUrl('pms/updateProduct');
    urlTree.queryParams = { 'id': productId }
    this.router.navigateByUrl(urlTree);
  }

  // TODO:日志的功能实现
  /**
   *
   * @param productId
   */
  handleShowLogs(productId: number) {
    console.log(productId);
  }

  handlePageSizeChange(e: number) {
    this.getProductsFromServer()

  }

  handlePageIndexChange(e: number) {
    this.getProductsFromServer()
  }

  // TODO: 商品删除功能实现
  handleDeleteProduct(productId: number) {
    this.modal.confirm({
      nzTitle: '确定删除此商品？',
      nzOkText: '确定',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: () => { },
      nzCancelText: '取消',
      nzMaskClosable: true,
    })
  }

  handleBatchOpterate() {
    if (!this.setOfCheckedId || this.setOfCheckedId.size < 1) {
      this.message.error('请选择要操作的商品', { nzDuration: 1000, nzPauseOnHover: true });
      return;
    }
    if (!this.batchOperate) {
      this.message.error('请选择操作', { nzDuration: 1000 })
      return;
    }
    this.modal.confirm({
      nzTitle: '是否进行批量操作？',
      nzOkText: '确定',
      nzOkType: 'primary',
      nzOnOk: this.applyatBchOperater,
      nzCancelText: '取消',
      nzMaskClosable: true,
    })
  }

  // TODO:批量操作功能的实现
  private applyatBchOperater = () => {
    switch (this.batchOperate) {
      case this.operateOptions[0].value:
        console.log(this.batchOperate);
        break;
      case this.operateOptions[1].value:
        console.log(this.batchOperate);
        break;
      case this.operateOptions[2].value:
        console.log(this.batchOperate);
        break;
      case this.operateOptions[3].value:
        console.log(this.batchOperate);
        break;
      case this.operateOptions[4].value:
        console.log(this.batchOperate);
        break;
      case this.operateOptions[5].value:
        console.log(this.batchOperate);
        break;
      case this.operateOptions[6].value:
        console.log(this.batchOperate);
        break;
      case this.operateOptions[7].value:
        console.log(this.batchOperate);
        break;
      default:
        console.error('未设定的批量操作');
    }

  }

  private updateCheckedSet(id: number, checked: boolean) {
    if (checked) {
      this.setOfCheckedId.add(id);
    } else {
      this.setOfCheckedId.delete(id);
    }
  }

  private refreshCheckedStatus() {
    const proudctId = this.products.map(item => item.id);
    this.thChecked = proudctId.every(id => this.setOfCheckedId.has(id));
    this.thIndeterminate = proudctId.some(id => this.setOfCheckedId.has(id)) && !this.thChecked;
  }
}
